<template>
  <div>
    <div class="search">
      <input type="text" class="search-input" placeholder="输入城市名或拼音" v-model="inputValue">
    </div>
    <div class="search-content" ref="search" v-show="inputValue">
      <ul>
        <li class="item" v-for="item in list" :key="item.id" @click="handleChangeClick(item.name)">{{item.name}}</li>
      </ul>
      <li class="item" v-show="listLength">未找到您输入的城市</li>
    </div>
  </div>
</template>

<script>
import Bscroll from 'better-scroll'
import { mapMutations } from 'vuex'
export default {
  props: {
    cities: Object
  },
  data () {
    return {
      inputValue: '',
      list: [],
      timer: null
    }
  },
  methods: {
    handleChangeClick (city) {
      this.changeCity(city)
      this.$router.push('/')
    },
    ...mapMutations(['changeCity'])
  },
  watch: {
    inputValue () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      this.timer = setTimeout(() => {
        if (this.inputValue.length === 0) {
          this.list = []
          return
        }
        const result = []
        for (const item in this.cities) {
          this.cities[item].forEach(value => {
            if (value.spell.indexOf(this.inputValue) > -1 || value.name.indexOf(this.inputValue) > -1) {
              result.push(value)
            }
          })
        }
        this.list = result
      }, 100)
    }
  },
  mounted () {
    this.scroll = new Bscroll(this.$refs.search)
  },
  computed: {
    listLength () {
      return !this.list.length
    }
  }
}
</script>

<style scoped lang="stylus">
 @import '~@/assets/css/varibles.styl';
 .search
  height .8rem
  padding 0 .1rem
  background $bgColor
  display flex
  flex-direction column
  justify-content center
  .search-input
    width 100%
    height .62rem
    line-height .62rem
    text-align center
    border-radius .08rem
    color #666
    font-size .28rem
    border none
.search-content
  position absolute
  top 1.6rem
  left 0
  right 0
  bottom 0
  overflow hidden
  background #ccc
  z-index 1
  .item
    list-style none
    line-height .6rem
    font-size .28rem
    padding-left .28rem
    border-bottom .02rem solid #ccc
    background #fff
</style>
